//
//  ImageSelectionController.m
//  TarPhone
//
//  Created by Christopher Anderson on 21/03/2009.
//  Copyright 2009 __MyCompanyName__. All rights reserved.
//

#import "ImageSelectionController.h"
#import "HeaderBackgroundView.h"
#import "MenuCellController.h"
#import "ImageSelectionTableCell.h"
#import "ImageChooser.h"

@implementation ImageSelectionController

@synthesize hostController;
@synthesize image;

- (id) initWithHostController:(UIViewController*)controller {
	self = [super init];
	if (self) {
		self.hostController = controller;
	}
	return self;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
	static NSString *imageCellIdentifier = @"ImageSelectionTableCell";
	
	cell = [tableView dequeueReusableCellWithIdentifier:imageCellIdentifier];
	if (cell == nil) {
        [[NSBundle mainBundle] loadNibNamed:@"ImageSelectionTableCell" owner:self options:nil];
	}
	cell.backgroundView = [[HeaderBackgroundView alloc] initWithFrame:CGRectZero indent:0 image:image];
	// Do something here if the user has already selected an image
	return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
	ImageChooser *imageChooser = [[ImageChooser alloc] initWithDelegate:self];
	[hostController presentModalViewController:imageChooser animated:YES];
	[imageChooser release];
}

// Image picker delegate stuff

- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingImage:(UIImage *)inImage editingInfo:(NSDictionary *)editingInfo { 
	NSLog(@"Image selected");
	[hostController dismissModalViewControllerAnimated:YES];
	
	ImageSelectionTableCell *imageCell = (ImageSelectionTableCell*) cell; 
	
	UIGraphicsBeginImageContext( imageCell.imageView.frame.size );
	[inImage drawInRect:imageCell.imageView.frame];
	//UIImage* resizedImage = UIGraphicsGetImageFromCurrentImageContext();
	UIGraphicsEndImageContext();
	
	//[imageCell.button setBackgroundImage:inImage forState:UIControlStateNormal];
	//[imageCell.imageView setImage:resizedImage];
	self.image = inImage;
	
	[imageCell.infoLabel setText:@"Change image"];
	
	//[imagePoster uploadImageToTarPipe:image withMimeType:@"image/png" workflow:workflow];
} 

- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker { 
	printf("User cancelled\n"); 
	[hostController dismissModalViewControllerAnimated:YES]; 
} 

- (UITableViewCellAccessoryType)tableView:(UITableView *)tableView accessoryTypeForRowWithIndexPath:(NSIndexPath *)indexPath {
	return UITableViewCellAccessoryNone;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
	return 120;
}


- (id) getData {
	return self.image;
}




@end
